{block name=body}
<h2 class="title">选择报告类型:</h2>
<select class="form-control" name="report" id="report" onchange="$('.report-input').hide();$('#'+$(this).val()).show();">
    <option value="classlist">选择一个报告类型</option>
    <optgroup label="课程报告">
        <option value="classlist">课程列表</option>
        <option value="limitedenrolments">Classes With Limited Enrolment</option>
        <option value="capacity">容量分析</option>
        <option value="enrolments">报名</option>
        <option value="enrolmentcomparison">报名比较</option>
        <option value="avgenrolment">平均入学率</option>
        <option value="memberdetails">会员的详细信息和地址</option>
        <!-- <option value="approvedenrolments">Approved Enrolments</option> -->
    </optgroup>
    <optgroup label="KPI报告">
        <option value="trialconversion">Trial Conversion Rate</option>
        <!-- <option value="triallist">Trial List</option> -->
        <option value="reenrolments">Re-enrolment Rate</option>
        <option value="toplocations">Top 10 Locations</option>
    </optgroup>
    <optgroup label="收入报告">
        <option value="revenue">Revenue</option>
        <option value="payments">Payments Received</option>
        <option value="dailypayment">Daily Payments</option>
        <option value="revenuecomparison">Revenue Comparison</option>
        <option value="averagerevenue">Average Revenue</option>
        <option value="studentstatus">Payment Status</option>
    </optgroup>
    <optgroup label="其他报告">
        <option value="referralsource">Referral Source</option>
        <option value="warnings">Warning Members</option>
        <option value="smsusage">SMS Usage</option>
    </optgroup>
</select>
<div class="form">
    <table class="table table-bordered table-striped table-hover" id="orders-table">
        <tbody>
        </tbody>
    </table>
</div>


<div class="report-input form" id="classlist" style="display:none;">
{include file='reports/input/input-classlist.tpl'}
</div>
<div class="report-input form" id="revenue" style="display:none;">
{include file='reports/input/input-revenue.tpl'}
</div>
<div class="report-input form" id="enrolments" style="display:none;">
{include file='reports/input/input-enrolments.tpl'}
</div>
<div class="report-input form" id="studentstatus" style="display:none;">
{include file='reports/input/input-studentstatus.tpl'}
</div>
<div class="report-input form" id="dailypayment" style="display:none;">
{include file='reports/input/input-dailypayments.tpl'}
</div>
<div class="report-input form" id="payments" style="display:none;">
{include file='reports/input/input-paymentsreceived.tpl'}
</div>
<div class="report-input form" id="reenrolments" style="display:none;">
{include file='reports/input/input-reenrolment.tpl'}
</div>
<div class="report-input form" id="trialconversion" style="display:none;">
{include file='reports/input/input-trialconversions.tpl'}
</div>
<div class="report-input form" id="triallist" style="display:none;">
{include file='reports/input/input-triallist.tpl'}
</div>
<div class="report-input form" id="enrolmentcomparison" style="display:none;">
{include file='reports/input/input-enrolmentcomparison.tpl'}
</div>
<div class="report-input form" id="revenuecomparison" style="display:none;">
{include file='reports/input/input-revenuecomparison.tpl'}
</div>
<div class="report-input form" id="averagerevenue" style="display:none;">
{include file='reports/input/input-avgrevenue.tpl'}
</div>
<div class="report-input form" id="avgenrolment" style="display:none;">
{include file='reports/input/input-avgenrolments.tpl'}
</div>
<div class="report-input form" id="capacity" style="display:none;">
{include file='reports/input/input-capacity.tpl'}
</div>
<div class="report-input form" id="referralsource" style="display:none;">
{include file='reports/input/input-referralsources.tpl'}
</div>
<div class="report-input form" id="toplocations" style="display:none;">
{include file='reports/input/input-toplocations.tpl'}
</div>
<div class="report-input form" id="warnings" style="display:none;">
{include file='reports/input/input-warnings.tpl'}
</div>
<div class="report-input form" id="limitedenrolments" style="display:none;">
{include file='reports/input/input-limitedenrolments.tpl'}
</div>
<div class="report-input form" id="smsusage" style="display:none;">
{include file='reports/input/input-smsusage.tpl'}
</div>
<div class="report-input form" id="memberdetails" style="display:none;">
{include file='reports/input/input-memberdetails.tpl'}
</div>

<form id="csv-form-saver" method="post" action="/admin/includes/processes/processes-file.php" style="display:none" target="_blank">
<input id="csv-filename" type="hidden" name="filename" value=""/><input id="csv-data" type="hidden" name="data" value=""/></form>
<script src="/admin/includes/js/jquery.validate.min.js"></script>
<script src="/admin/includes/js/custom.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $("#to").datepicker({
        changeMonth : true,
        changeYear : true,
        dateFormat : "dd/mm/yy",
        maxDate : new Date(),
        onSelect : function(selectedDate) {
            $("#from").datepicker("option", "maxDate", selectedDate);
        }
    });

    $("#from").datepicker({
        changeMonth : true,
        changeYear : true,
        dateFormat : "dd/mm/yy",
        maxDate : new Date(),
        onSelect : function(selectedDate) {
            $("#to").datepicker("option", "minDate", selectedDate);
        }
    });

    $('#filter-form').validate();

    $('#status').change(function(){
        if ( $(this).val() == 0 ) {
            $('.order').show();
        } else {
            $('.order').hide();
            $('.'+ $(this).val() ).show();
        }
        checkVisible();
    });

    $('.term-filter').change(function(){
        filterLocations($(this).closest('form'));
    }); 
    $('.region-filter').change(function(){
        filterLocations($(this).closest('form'));
    }); 
});

function filterLocations(PARENT){
    var termregions = '';
    $('option:selected', PARENT.find('.term-filter')).each(function(){
        termregions += '&' + encodeURIComponent('termregions[]')+'='+$(this).attr('data-termregion');  
        });
    var regions = '';
    $('option:selected', PARENT.find('.region-filter')).each(function(){
        regions += '&' + encodeURIComponent('regions[]')+'='+$(this).attr('value');  
        });
    var LOC = PARENT.find('.location-filter');
    $('body').css('cursor', 'wait');
    $.ajax({
        type : "POST",
        url : "/admin/includes/processes/processes-reports.php",
        cache : false,
        data : 'action=locationsfilter'+termregions+regions,
        dataType : "html",
        success : function(data, textStatus) {
            try {
                var obj = $.parseJSON(data);
                    LOC.empty();
                    $.each(obj.locationlist, function(key,value) {
                        LOC.append($("<option></option>").attr("value", value['id']).text(value['value']));
                    });
            } catch (err) {}
            $('body').css('cursor', 'default');
        },
        error: function(){
            $('body').css('cursor','default'); 
            console.log('AJAX error');
        }
    });
}

function printArea(divname) {
     var printContents = document.getElementById(divname).innerHTML;
     var originalContents = document.body.innerHTML;
     document.body.innerHTML = printContents;
     window.print();
     document.body.innerHTML = originalContents;
}
</script>

<script type="text/javascript">
function exportPageToCSV(link,page, filename) {
  
  var $terms = $(page).find('.term');
  var csv = "";
  $terms.each(function(data){
      var $title = $(this).find('.title').first();
    csv += '"'+$title.text().replace('"', '""') + '"\r\n';
    var $locations = $(this).find('.location');
        if($locations.length){ 
        $locations.each(function(data){
            var $title = $(this).find('.title').first();
          csv += '"'+$title.text().replace('"', '""') + '"\r\n';
          csv += exportTableToCSV($(this)) + '\r\n';
        });
        }else{
            csv += exportTableToCSV($(this).find('table')) + '\r\n';
        }
  });
  
  // Data URI
    csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csv);
    var a = document.createElement('a');
    if (typeof a.download != "undefined") {
      $(link).attr({ 'download': filename, 'href': csvData, 'target': '_blank' });
    }else{
        $('#csv-form-saver').find('#csv-filename').val(filename);
        $('#csv-form-saver').find('#csv-data').val(csvData);
        $('#csv-form-saver').submit();
    }
}

function exportTableToCSV($table) {

    //var $rows = $table.find('tr:has(td)'), //Change made to list all th records as well as td
        var $rows = $table.find('tr'),

        // Temporary delimiter characters unlikely to be typed by keyboard
        // This is to avoid accidentally splitting the actual contents
        tmpColDelim = String.fromCharCode(11), // vertical tab character
        tmpRowDelim = String.fromCharCode(0), // null character

        // actual delimiter characters for CSV format
        colDelim = '","',
        rowDelim = '"\r\n"',

        // Grab text from table into CSV formatted string
        csv = '"' + $rows.map(function (i, row) {
            var $row = $(row),
                $cols = $row.find('td,th'); //Change made to list all th records as well as td

            return $cols.map(function (j, col) {
                var $col = $(col),
                    text = $col.text();

                return text.replace('"', '""'); // escape double quotes

            }).get().join(tmpColDelim);

        }).get().join(tmpRowDelim)
            .split(tmpRowDelim).join(rowDelim)
            .split(tmpColDelim).join(colDelim) + '"';

    return csv;
}

var downloadDataURI = function($, options) {
    if(!options)
        return;
    $.isPlainObject(options) || (options = { data: options });
    if(!$.browser.webkit) 
        window.location = options.data;
    options.filename || (options.filename = "download." + options.data.split(",")[0].split(";")[0].substring(5).split("/")[1]);
    options.url || (options.url = "http://download-data-uri.appspot.com/");
    $('<form method="post" action="'+options.url+'" style="display:none"><input type="hidden" name="filename" value="'+options.filename+'"/><input type="hidden" name="data" value="'+options.data+'"/></form>').submit().remove();
}
</script>

{/block}
